<template>
	<view class="container">
		<!-- 资讯分类 固定顶部 -->
		<view class="news-tabs-fixed-fixed">
			<view class="custom-segmented">
				<view
					v-for="(tab, idx) in tabs"
					:key="idx"
					:class="['custom-segmented-item', currentTab === tab.id ? 'active' : '']"
					@click="onTabChange(tab)"
				>
					{{ tab.name }}
				</view>
			</view>
		</view>
		<!-- 资讯列表 -->
		<scroll-view 
			class="news-list-scroll" 
			scroll-y="true" 
			:style="{height: scrollViewHeight + 'px'}"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
			@scrolltolower="onLoadMore"
			:lower-threshold="100"
			:enable-back-to-top="true"
		>
			<view v-for="(item, idx) in newsList" :key="item.id || idx" class="news-item" @click="goNewsInfo(item)">
				<view class="news-img-container">
					<image 
						:src="getThumb(item)" 
						class="news-img" 
						:lazy-load="true"
						@error="onImageError"
					/>
				</view>
				<view class="news-content">
					<view class="news-content-top">
						<view class="news-title">{{ item.title || item.newsTitle || '未命名资讯' }}</view>
						<view class="news-desc">{{ item.summary || item.desc || item.intro || '' }}</view>
					</view>
					<view class="news-date">{{ formatDate(item.publishTime || item.date || item.createTime) }}</view>
				</view>
			</view>
			
			<!-- 加载状态 -->
			<view class="load-status" v-if="loadingMore">
				<view class="loading-spinner"></view>
				<text>加载中...</text>
			</view>
			<view class="load-status" v-else-if="!hasMore && newsList.length > 0">
				<text>没有更多了</text>
			</view>
			<view class="load-status" v-else-if="!loading && newsList.length === 0">
				<text>暂无数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { API } from '@/utils/api.js'
	import { processNewsUrls } from '@/utils/url-helper.js'
	export default {
		data() {
			return {
				currentTab: '',
				tabs: [],
				newsList: [],
				page: 1,
				size: 10,
				loading: false,
				loadingMore: false,
				isRefreshing: false,
				hasMore: true,
				categories: [],
				scrollViewHeight: 0
			}
		},
		mounted() {
			const self = this;
			uni.getSystemInfo({
				success: function(res) {
					self.scrollViewHeight = res.windowHeight - 60
				}
			})
			this.fetchCategories()
		},
		// 添加分享功能
		onShareAppMessage() {
			const currentTabName = this.tabs.find(tab => tab.id === this.currentTab)?.name || '全部'
			return {
				title: `最新资讯 - ${currentTabName}`,
				path: '/pages/news/news',
				imageUrl: '/static/assets/share/news-share.png'
			}
		},
		// 分享到朋友圈
		onShareTimeline() {
			const currentTabName = this.tabs.find(tab => tab.id === this.currentTab)?.name || '全部'
			return {
				title: `最新资讯 - ${currentTabName}`,
				imageUrl: '/static/assets/share/news-share.png'
			}
		},
		methods: {
			onTabChange(e) {
				this.currentTab = e.id
				this.page = 1
				this.hasMore = true
				this.newsList = [] // 清空列表
				this.fetchNews(true)
			},
			async fetchCategories() {
				try {
					const res = await API.news.getCategoryList()
					const list = res?.rows || []
					this.tabs = [{ id: '', name: '全部' }].concat(list)
				} catch (e) {
					console.warn('获取资讯分类失败，使用默认分类', e)
					this.tabs = [{ id: '', name: '全部' }]
				} finally {
					this.page = 1
					this.hasMore = true
					this.fetchNews(true)
				}
			},
			async fetchNews(reset = false) {
				if (this.loading) return
				
				this.loading = true
				if (!reset) {
					this.loadingMore = true
				}
				
				try {
					const params = { page: this.page, size: this.size }
					if (this.currentTab) {
						params.typeId = this.currentTab
					}
					
					const res = await API.news.getList(params)
					const list = res?.rows || []
					
					// 处理URL
					const processedList = processNewsUrls(list)
					
					if (reset) {
						this.newsList = processedList
					} else {
						this.newsList = this.newsList.concat(processedList)
					}
					
					// 判断是否还有更多数据
					this.hasMore = Array.isArray(list) && list.length >= this.size
					if (this.hasMore) {
						this.page += 1
					}
				} catch (e) {
					console.error('加载资讯失败:', e)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.loadingMore = false
					if (this.isRefreshing) {
						this.isRefreshing = false
					}
				}
			},
			onRefresh() {
				this.isRefreshing = true
				this.page = 1
				this.hasMore = true
				this.fetchNews(true)
			},
			async onLoadMore() {
				if (this.loadingMore || this.loading || !this.hasMore) return
				await this.fetchNews(false)
			},
			goNewsInfo(item) {
				const id = item.id || item.newsId
				if (!id) {
					uni.showToast({
						title: '资讯ID不存在',
						icon: 'none'
					})
					return
				}
				uni.navigateTo({ url: '/pages/news/newsInfo?id=' + id })
			},
			getThumb(item) {
				const thumb = item?.thumbnailUrl || item?.coverUrl || item?.img || ''
				// 如果没有缩略图，返回默认图片
				return thumb || '/static/images/default-news.png'
			},
			onImageError(e) {
				console.log('图片加载失败:', e)
				// 可以设置默认图片
			},
			formatDate(value) {
				if (!value) return ''
				try {
					const d = typeof value === 'number' ? new Date(value) : new Date(String(value).replace(/-/g, '/'))
					const y = d.getFullYear()
					const m = (d.getMonth() + 1).toString().padStart(2, '0')
					const day = d.getDate().toString().padStart(2, '0')
					return `${y}-${m}-${day}`
				} catch (e) {
					return String(value)
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		background: #f5f5f5;
		min-height: 100vh;
		position: relative;
		overflow: hidden;
	}

	/* 固定顶部的资讯分类 */
	.news-tabs-fixed-fixed {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		z-index: 100;
		background: #ffffff;
		padding: 20rpx 0 8rpx 0;
		border-bottom: 1rpx solid #e8e8e8;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	/* 自定义分段器样式 */
	.custom-segmented {
		display: flex;
		background: #ffffff;
		border-radius: 32rpx;
		overflow-x: auto;
		overflow-y: hidden;
		margin: 0 16rpx;
		white-space: nowrap;
		gap: 25rpx;
		padding: 8rpx 0;
	}
	
	.custom-segmented-item {
		flex-shrink: 0;
		text-align: center;
		padding: 12rpx 30rpx;
		font-size: 24rpx;
		color: #1c1c29;
		background: #ffffff;
		border-radius: 32rpx;
		transition: all 0.3s ease;
		min-width: fit-content;
		border: 1rpx solid #e8e8e8;
		white-space: nowrap;
	}
	
	.custom-segmented-item.active {
		background: #C6282B;
		color: #fff;
		border-color: #C6282B;
		transform: scale(1.05);
	}

	/* 资讯列表滚动区域 */
	.news-list-scroll {
		margin-top: 120rpx;
		padding: 20rpx 0;
	}

	/* 新闻item - 优化高度，参考iPhone 14 Pro */
	.news-item {
		display: flex;
		background: #ffffff;
		border-radius: 16rpx;
		margin: 12rpx 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
		align-items: center;
		height: 200rpx; /* 减少高度到200rpx */
		overflow: hidden;
		transition: transform 0.2s ease, box-shadow 0.2s ease;
	}

	.news-item:active {
		transform: scale(0.98);
		box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.12);
	}

	.news-img-container {
		width: 280rpx;
		height: 160rpx;
		margin: 20rpx 16rpx;
		border-radius: 12rpx;
		overflow: hidden;
		flex-shrink: 0;
		background: #f0f0f0;
		position: relative;
	}

	.news-img {
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
		object-fit: aspectFill; 
	}

	/* 内容区域 */
	.news-content {
		flex: 1;
		padding: 20rpx 16rpx 20rpx 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 160rpx; /* 与图片高度一致 */
		overflow: hidden;
	}

	.news-content-top {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.news-title {
		font-weight: 600;
		font-size: 28rpx; /* 稍微减小字体 */
		line-height: 1.4;
		color: #1a1a1a;
		margin-bottom: 8rpx; /* 减少间距 */
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.news-desc {
		color: #666;
		font-size: 22rpx; /* 减小字体 */
		line-height: 1.4; /* 减小行高 */
		display: -webkit-box;
		-webkit-line-clamp: 2; /* 减少行数 */
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		flex: 1;
	}

	.news-date {
		color: #999;
		font-size: 20rpx; /* 减小字体 */
		margin-top: 8rpx; /* 减少间距 */
		flex-shrink: 0;
	}

	/* 加载状态样式 */
	.load-status {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.loading-spinner {
		width: 32rpx;
		height: 32rpx;
		border: 3rpx solid #f3f3f3;
		border-top: 3rpx solid #C6282B;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-right: 16rpx;
	}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	/* iPhone 14 Pro 优化 */
	@media screen and (max-width: 750rpx) {
		.news-item {
			margin: 10rpx 16rpx;
			height: 180rpx; /* 小屏幕下进一步减少高度 */
		}
		
		.news-img-container {
			width: 240rpx;
			height: 140rpx;
			margin: 20rpx 12rpx;
		}
		
		.news-content {
			padding: 20rpx 12rpx 20rpx 0;
			height: 140rpx;
		}
		
		.news-title {
			font-size: 26rpx;
			margin-bottom: 6rpx;
		}
		
		.news-desc {
			font-size: 20rpx;
			-webkit-line-clamp: 2;
		}
		
		.news-date {
			font-size: 18rpx;
			margin-top: 6rpx;
		}
	}

	/* 超小屏幕优化 */
	@media screen and (max-width: 600rpx) {
		.news-item {
			height: 160rpx;
		}
		
		.news-img-container {
			width: 200rpx;
			height: 120rpx;
		}
		
		.news-content {
			height: 120rpx;
		}
		
		.news-title {
			font-size: 24rpx;
			-webkit-line-clamp: 1;
		}
		
		.news-desc {
			font-size: 18rpx;
			-webkit-line-clamp: 1;
		}
	}
</style>